<?php
namespace Admin\Controller;
use Common\Controller\AdminBaseController;
class UserController extends AdminBaseController{
	public function index(){
		$title = I('get.title/s','');
		$page = I('get.page/d',1);//通过前台获取当前页默认为第一页
		$users = M('Admin');
		$whereSql = !empty($title) ? 'name like "%'.$title.'%" or realname like "%'.$title.'%"' : '';
		//搜索分页
		//第一种原生的tp自带的分页;
		//第二种是在tp的基础上修改core/libary/think/page.class.php再将样式复制到user_index.html参见白俊遥的博客
		//$count = $users -> where($whereSql)->count();// 查询满足要求的总记录数
		// $page = new \Think\Page($count,5,['title' => $title]);
		// // $page -> setConfig('prev','上一页');
		// // $page -> setConfig('next','下一页');
		// $show = $page -> show();
		// $list = $users->where($whereSql)->order('id asc')-> limit($page->firstRow.','.$page->listRows)->select();
		// $this -> assign('page',$show);
		//第三种是js和php配合
		$pageCount = 5;//每页显示5条
		$count = $users -> where($whereSql)->count();// 查询满足要求的总记录数
		$countnum = ceil($count / $pageCount);//总页码数
		$fRow = empty($page - 1) ? 0 : (($page - 1) * $pageCount);
		// $list = $users -> fetchSql(true) ->where($whereSql) -> order('id asc') -> limit($fRow,$pageCount) -> select();调试打印sql语句
		// echo $list;
		$list = $users ->alias('a') -> field('a.id,a.name,a.img,a.realname,a.loginnum,a.logintime,a.status,g.title') -> join('left join dx_admin_group ag on a.id = ag.uid left join dx_group g on ag.group_id = g.id') ->where($whereSql) -> order('a.id asc') -> limit($fRow,$pageCount) -> select();

		$this -> assign('countnum',$countnum);
		$this->assign('list',$list);
		$this->assign('title',$title);//等价于$this->title = $title
		$this -> display();
	}
	
	//第四种分页
	public function listpage(){
		sleep(2);
		$title = I('post.title/s','');
		$page = I('post.page/d',1);
		$admin = M('Admin');
		$numlist = 5;
		$whereSql = empty($title) ? '' : 'name like "%'.$title.'%" or realname like "%'.$title.'%"';
		$totalnum = $admin -> where($whereSql) -> count();
		$pagenum = ceil($totalnum / $numlist);
		$fRow = ($page - 1) * $numlist;
		$list = $admin -> where($whereSql) -> order('id asc')  -> limit($fRow,$numlist) -> select();
		$listTr = '';
		foreach ($list as $k => $v) {
			$listTr .= '<tr><td>'.$v['id'].'</td>'. '<td>'.$v['name'].'</td>'.'<td>'.$v['id'].'</td>'.'<td>'.$v['rule'].'</td>'.'<td>'.$v['loginnum'].'</td>'.'<td>'.$v['logintime'].'</td>'.'<td>'.$v['realname'].'</td><td>';
			if($v['status']){
				$listTr .= '<a href="javascript:changeState('.$v['id'].')" id="state.'.$v['id'].'" class="label label-primary">正常</a>';
			}else{
				$listTr .= '<a href="javascript:changeState('.$v['id'].')" id="state.'.$v['id'].'" class="label label-primary">禁用</a>';
			} 
			$listTr .= '</td><td><a href="'.U('User/edit?id='.$v['id']).'" class="label label-primary"><i class="fa fa-edit"></i> 修改</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:del('.$v['id'].');" class="label label-danger"><i class="fa fa-trash"></i> 删除</a></td></tr>';

		}
		$res = ['pagenum' => $totalnum ,'content' => $listTr];
		exit(json_encode($res));
	}

	//添加管理员
	public function add(){
		$group = M('group');
		$opt = $group -> field('id,title') -> where('status = 1') -> select();//从group读出角色
		$this -> assign('opt',$opt);//循环前端页面option
		$this -> display();
	}
	//添加保存管理员
	public function addsave(){
		if(IS_AJAX || IS_POST){
			$username = I('post.username/s','');
			if(!$username){
				$this->ajaxReturn(['stauts' => 0, 'mess' => '账号不能为空！']);
			}
			$pid = I('post.pid/s',0);
			//获取密码
			$pwd = I('post.password/s','');
			if(!$pwd){
				$this->ajaxReturn(['status' => 0, 'mess' => '密码不能为空！']);
			}
			//获取真实姓名
			$realname = I('post.realname/s','');
			if(!$realname){
				$this -> ajaxReturn(['status' => 0, 'mess' => '真实姓名不能为空！']);
			}
			$status = I('post.status/d');
			$imgPath = '';
			//如果传过来的文件数组不为空就进行上传文件函数过滤
			if(!empty($_FILES)){
				$imgPath = uploadFile($_FILES['img']);
			}
			if(is_array($imgPath)){
				$this -> ajaxReturn($imgPath);
			}

			//去数据库查询看有没有重复的用户名
			$admin = M('Admin');
			$adminAdd = $admin -> where(['name' => $username]) -> find();
			if($adminAdd){
				$this -> ajaxReturn(['status' => 0, 'mess' => '用户名已经存在！']);
			}
			//将获取的数据添加到数据库
			$data = ['name' => $username , 'pwd' => _md5($pwd), 'realname' => $realname, 'status' => $status ,'img' => $imgPath];

			$admin -> startTrans();//开启事务
			$mid = $admin -> add($data);//添加到dx_admin的表
			if(!$mid){
				$admin -> rollback();//如果没有添加成功将采取事务回滚
			}
			$mid = $admin -> getLastInsID();//通过函数获取最后一次添加的id
			$adminG = M('AdminGroup');//查询用户组和用户角色
			$is_ag = $adminG -> add(['uid' => $mid,'group_id' => $pid]);//向dx_admim_group添加数据
			if($is_ag){
				$admin -> commit();//成功就提交
			}else{
				$admin -> rollback();//处理失败就回滚
			}
			//看添加的动作执行是否成功相当于if($query)()
			if($mid === false){
				$this -> ajaxReturn(['status' => 0, 'mess' => '添加失败']);
			}
			$this -> ajaxReturn(['status' => 1, 'mess' => '添加成功']);	
		}
	}
	//修改管理员
	public function edit(){
		if(IS_GET){
			$id = I('get.id/d',0);
			if(!$id){
				$this -> error('非法操作!');
			}
			$getAdmin = M('Admin') -> alias('a') -> field('a.id,a.name,a.realname,a.status,ag.group_id') -> join('left join dx_admin_group ag on a.id = ag.uid') -> where(['id' => $id]) -> find();
			$getGroup = M('Group') -> field('id,title') -> where('status = 1') -> select();
			$this -> assign('getAdmin',$getAdmin);
			$this -> assign('getGroup',$getGroup);
			$this -> display();
		}
	}	
	//修改保存管理员
	public function editsave(){
		if(IS_AJAX || IS_POST){
			$id = I('post.id',0);
			//修改是通过id来修改更新，如果有就进行验证判断提交过来的信息
			if($id){
				//不能修改管理员账号
				$realname = I('post.realname/s','');
				$pid = I('post.pid/s',0);
				$status = I('post.status/d',0);
				$admin = M('Admin');
				$adminEdit = $admin -> where(['id' => $id]) -> find();
				//判断通过id传过来修改的用户是否存在
				if(empty($adminEdit)){
					$this -> ajaxReturn(['status' => 0, 'mess' => '用户不存在，无法修改！']);
				}
				$imgPath = '';
				// dump($_FILES);exit;
				if(!empty($_FILES)){
					$imgPath = uploadFile($_FILES['img']);
				}
				//后台判断传过来的pid 真是姓名和头像都为空的时候就是没有修改什么直接保存
				if(empty($pid) && empty($realname) && empty($imgPath)){
					$this -> ajaxReturn(['status' => 1, 'mess' => '修改成功!']);
				}
				if(!empty($pid) && empty($realname) && empty($imgPath)){
					$is_group = M('AdminGroup') -> add(['uid' => $id,'group_id' => $pid],[],true);
					//添加时如果存在会覆盖 
					if(!$is_group){
						$this -> ajaxReturn(['status' => 0, 'mess' => '修改失败！']);
					}
					$this -> ajaxReturn(['status' => 1, 'mess' => '修改成功！']);
				}
				if(empty($pid) && (!empty($realname) || !empty($imgPath))){
					$data = [];
					if(!empty($realname)){
						$data['realname'] = $realname;
					}
					if(!empty($imgPath)){
						$data['img'] = $imgPath;
					}
					// dump($data);exit;
					$is_admin = $admin -> where('id='.$id) -> setField($data);
					if(!$is_admin){
						$this -> ajaxReturn(['status' => 0, 'mess' => '修改失败！']);
					}
					$this -> ajaxReturn(['status' => 1, 'mess' => '修改成功！']);
				} 
				//都不为空的时候对两个表进行操作需要事务，一个表不需要事务
				$admin -> startTrans();
				$data = [];
				if(!empty($realname)){
					$data['realname'] = $realname;
				}
				if(!empty($imgPath)){
					$data['img'] = $imgPath;
				}
				//更新admin表
				$is_adminup = $admin -> where(['id' => $id]) -> setField($data);
				// echo $is_adminup;exit;
				if(!$is_adminup){
					$admin -> rollback();
				}
				$is_group = M('AdminGroup') -> add(['uid' => $id,'group_id' => $pid],[],true);
				if(!$is_group){
					$admin -> rollback();
				}
				$admin -> commit();
				$mid = true;//如果什么都没有修改就直接提交保存
			}else{
				//没有id就提示错误
				$this -> ajaxReturn(['stauts' => 0, 'mess' => '数据操作错误！']);
			}
			if($mid === false){
				$this -> ajaxReturn(['status' => 0, 'mess' => '修改失败']);
			}
			$this -> ajaxReturn(['status' => 1,'mess' => '修改成功']);
		}
	}

	public function del(){
		if(IS_POST){
			$id = I('post.id/d',0);
			if(empty($id) || (1 == $id)){
				$this->ajaxReturn(['status' => 0,'mess' => '非法操作']);
			}else{
				$admin = M('Admin');
				$admin->startTrans();
				$is_delA = $admin -> where(['id' => $id]) ->delete(); 
				if(!$is_delA){
					$admin -> rollback();
					$this->ajaxReturn(['status' => 0 , 'mess' => '删除失败!']);
				}
				$is_delG = M('AdminGroup') -> where(['uid' => $id]) -> delete(); 
				if(!$is_delG){
					$admin->rollback();
					$this->ajaxReturn(['status' => 0 , 'mess' => '删除失败!']);
				}
				$admin -> commit();
				$this->ajaxReturn(['status' => 1,'mess' => '删除成功!']);
			}
		}else{
			$this->ajaxReturn(['status' => 0,'mess' => '非法操作!']);
		}
	}

	//与前端的检测状态进行交互改变数据管理员当前的状态
	public function Alterstate(){
		//检测是否是post提交
		if(IS_POST){
			$id = I('post.id/d',0);
			if(empty($id) || (1 == $id)){
				$this->ajaxReturn(['status' => 0,'mess'=>'非法操作!']);
			}
			$adminInfo = M('Admin')->field('status')->where(['id' => $id])->find();
			//从后台查询status字段，如果字段status为0就设置字段为1，如果字段有值为1就设置为0，empty($adminInfo['status']) 他等于 $adminInfo == 0
			if(empty($adminInfo['status'])){
				M('Admin')->where(['id' => $id])->setField('status',1);//更新字段为1
				$this->ajaxReturn(['status' => 1,'mess' => '已开启' ,'data' => 1]);
			}else{
				M('Admin')->where(['id' => $id])->setField('status',0);
				$this->ajaxReturn(['stauts' => 1,'mess' => '已禁用','data' => 0]);
			}
		}else{
			$this->ajaxReturn(['status' => 0, 'mess' => '非法操作!']);
		}
	}
	
}
